package com.qf.servlet;

import com.qf.Utils.DaoUtils;
import com.qf.entity.Admin;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String inputcode=req.getParameter("code");
        HttpSession session=req.getSession();
        String imagecode=(String)session.getAttribute("code");
        long codetime=(long)(session.getAttribute("code_creatTime"));
        if(username==null||password==null||username.equals("")||password.equals("")){
            resp.sendRedirect("login.jsp?status=1");
            return;
        }
        if(inputcode==null||inputcode.equals("")||(!inputcode.equals(imagecode))){
            resp.sendRedirect("login.jsp?status=3");
            return;
        }
        if((System.currentTimeMillis()-codetime)>60*1000){
            resp.sendRedirect("login.jsp?status=4");
            return;
        }
        Admin admin= DaoUtils.checkAdmin(username,password);
        if(admin!=null){
            session.setAttribute("user_login",admin);
            session.removeAttribute("code");
            session.removeAttribute("code_creatTime");
            resp.sendRedirect("newIndex.jsp");
        }else{
            resp.sendRedirect("login.jsp?status=2");
        }
    }
}
